package com.app.business.web.business;

import com.app.business.calculate.CalculateUtils;
import com.app.business.en.Status;
import com.app.business.model.*;
import com.app.business.service.*;
import com.app.system.jpa.PageBean;
import com.app.system.permission.model.DataDict;
import com.app.system.permission.model.SysRole;
import com.app.system.permission.service.DataDictService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.DateUtils;
import com.app.system.utils.dataType.IntegerUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.AjaxException;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 安置协议签署
 * Created by lsh on 2019/2/14.
 */
@Controller
@RequestMapping("/business/resetAgreement/*")
public class ResetAgreementController {

    @Autowired
    private ContractService contractService;
    @Autowired
    private DataDictService dataDictService;
    @Autowired
    private HouseService houseService;
    @Autowired
    private BuyHousePersonService buyHousePersonService;
    @Autowired
    private CarLotService carLotService;
    @Autowired
    private CarLotBuyPersonService carLotBuyPersonService;
    @Autowired
    private StorageRoomPersonService storageRoomPersonService;
    @Autowired
    private HouseBuyPersonService houseBuyPersonService;
    @Autowired
    private StorageRoomService storageRoomService;
    @Autowired
    private ActionHistoryService actionHistoryService;
    @Autowired
    private ShopHouseService shopHouseService;
    @Autowired
    private ShopHouseBuyPersonService shopHouseBuyPersonService;

    /**
     * 安置协议列表
     */
    @RequestMapping("resetAgreementList")
    @RequiresPermissions("resetAgreement:resetAgreementList")
    public void list() {
    }

    /**
     * 加载安置协议列表
     *
     * @return
     */
    @RequestMapping("loadResetAgreementList")
    @ResponseBody
    @RequiresPermissions("resetAgreement:loadResetAgreementList")
    public Map loadContractList() {
        List<Map> listData = Lists.newArrayList();
        PageBean<Contract> contractPageBean = this.contractService.getChoosedHousePageBean();
        List<Contract> contractList = contractPageBean.getDatas();
        Map<String, DataDict> signMap = this.dataDictService.getMapByParentNameForValue("签约状态");
        Map<String, DataDict> checkMap = this.dataDictService.getMapByParentNameForValue("复核状态");
        Map<String, DataDict> townMap = this.dataDictService.getMapByParentNameForValue("乡镇");
        Map<String, DataDict> settleMap = this.dataDictService.getMapByParentNameForValue("财务结清状态");

        if (!CollectionUtils.isEmpty(contractList)) {
            Map<String, Object> item = null;
            for (Contract contract : contractList) {
                item = null;
                item = Maps.newHashMap();
                item.put("id", contract.getId());
                item.put("town", StringUtils.dataDictShow(townMap.get(contract.getZsProject().getTown())));
                item.put("zsProjectName", contract.getZsProject().getProjectName());
                item.put("contractCode", StringUtils.getNotNull(contract.getContractCode()));
                item.put("name", StringUtils.getNotNull(contract.getName()));
                item.put("chooseHouseNum", StringUtils.getNotNull(contract.getChooseHouseNum()));
                item.put("limitHouseAreaTotal", BigDecimalUtils.getNotNullStr(contract.getLimitHouseAreaTotal()));
                item.put("azSignStatus", IntegerUtils.getNotNull(contract.getAzSignStatus()));
                item.put("azSignStatusStr", StringUtils.dataDictShow(signMap.get(IntegerUtils.getNotNull(contract.getAzSignStatus()).toString())));
                item.put("azSignDate", contract.getAzSignStatus().equals(Status.NO.getIndex()) ? "" : DateUtils.dateToStringDefault(contract.getAzSignDate()));
                item.put("financeCheckStatus", IntegerUtils.getNotNull(contract.getFinanceCheckStatus()));
                item.put("financeSettleStatusStr", StringUtils.dataDictShow(settleMap.get(IntegerUtils.getNotNull(contract.getFinanceSettleStatus()).toString())));
                item.put("financeCheckStatusStr", StringUtils.dataDictShow(checkMap.get(IntegerUtils.getNotNull(contract.getFinanceCheckStatus()).toString())));
                listData.add(item);
            }
        }
        return LayUiUtils.page(contractPageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 安置协议打印
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("printResetAgreement")
    @RequiresPermissions("resetAgreement:printResetAgreement")
    public void printHouse(HttpServletRequest request, ModelMap modelMap) {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "1111", "数据错误！");

        List<House> houseList = this.houseService.getHouseListByContractId(contractId);
        List<CarLot> carLotList = this.carLotService.getCarLotListByContractId(contract.getId());
        List<StorageRoom> noHouseStorageRoomList = this.storageRoomService.getNoHouseStorageRoomListByContractId(contract.getId());
        List<ShopHouse> shopHouseList = this.shopHouseService.getShopHouseListByContractId(contract.getId());
        modelMap.addAttribute("contract", contract);
        modelMap.addAttribute("houseList", houseList);
        modelMap.addAttribute("carLotList", carLotList);
        modelMap.addAttribute("noHouseStorageRoomList", noHouseStorageRoomList);
        modelMap.addAttribute("shopHouseList",shopHouseList);

    }


    /**
     * 安置协议签约（可撤销）
     *
     * @param request
     */
    @RequestMapping("azSign")
    @ResponseBody
    @RequiresPermissions("resetAgreement:azSign")
    public synchronized Response azSign(HttpServletRequest request) {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "1111", "数据错误！");
        if (contract.getAzSignStatus().equals(Status.NO.getIndex()) || contract.getAzSignStatus().equals(Status.TUI.getIndex())) {
            Precondition.checkAjaxArguement(contract.getChooseHouseStatus().equals(Status.YES.getIndex()), "2222", "该户未签认，暂不能设置签约！");
            contract.setAzSignStatus(Status.YES.getIndex());
            contract.setAzSignDate(new Date());
            contract.setLimitStatus(2);
            this.actionHistoryService.saveActionHistoryByContractId(contract.getId(), "设置为已签约状态", "安置协议签约");

        } else {
            Precondition.checkAjaxArguement(contract.getLimitStatus() == 1, "1111", "领导未授权，请先授权！");
            Precondition.checkAjaxArguement(contract.getFinanceSettleStatus() != null && !contract.getFinanceSettleStatus().equals(Status.YES.getIndex()), "2222", "财务已结算，如需退回请联系财务！");
            contract.setAzSignStatus(Status.TUI.getIndex());
            contract.setAzSignDate(new Date());
            this.actionHistoryService.saveActionHistoryByContractId(contract.getId(), "设置为退回状态", "安置协议签约");

        }
        this.contractService.save(contract);
        return new Response("0001", "操作成功");
    }

    /**
     * 安置协议打印
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("chooseBuyPersonList")
    @RequiresPermissions("resetAgreement:chooseBuyPersonList")
    public void chooseBuyPersonList(HttpServletRequest request, ModelMap modelMap) {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkSqdsArguement(contract != null, "数据错误！");
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        Integer carLotId = ParamUtils.getInt(request, "carLotId", 0);
        Integer storageRoomId = ParamUtils.getInt(request, "storageRoomId", 0);
        Integer shopHouseId = ParamUtils.getInt(request, "shopHouseId", 0);

        if (houseId != 0) {
            House house = this.houseService.findOne(houseId);
            modelMap.addAttribute("house", house);
        } else if (carLotId != 0) {
            CarLot carLot = this.carLotService.findOne(carLotId);
            modelMap.addAttribute("carLot", carLot);
        } else if (storageRoomId != 0) {
            StorageRoom storageRoom = this.storageRoomService.findOne(storageRoomId);
            modelMap.addAttribute("storageRoom", storageRoom);
        } else  if (shopHouseId != 0) {
            ShopHouse shopHouse = this.shopHouseService.findOne(shopHouseId);
            modelMap.addAttribute("shopHouse",shopHouse);
        }
        modelMap.addAttribute("contract", contract);
        modelMap.addAttribute("carLotId", carLotId);
        modelMap.addAttribute("houseId", houseId);
        modelMap.addAttribute("shopHouseId",shopHouseId);
        modelMap.addAttribute("storageRoomId", storageRoomId);
    }

    /**
     * 加载购房人列表数据
     *
     * @return
     */
    @RequestMapping("loadChooseBuyPersonList")
    @ResponseBody
    @RequiresPermissions("resetAgreement:loadChooseBuyPersonList")
    public Map loadChooseBuyPersonList(HttpServletRequest request) {
        List<Map> listData = Lists.newArrayList();
        int contractId = ParamUtils.getInt(request, "contractId", 0);
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        Integer carLotId = ParamUtils.getInt(request, "carLotId", 0);
        Integer storageRoomId = ParamUtils.getInt(request, "storageRoomId", 0);
        Integer shopHouseId = ParamUtils.getInt(request, "shopHouseId", 0);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "1111", "数据错误！");
        List<String> buyHousePersonIdList = new ArrayList<>();
        if (houseId != 0) {
            buyHousePersonIdList = this.houseBuyPersonService.getBuyHousePersonIdListByHouseId(houseId);
        } else if (carLotId != 0) {
            buyHousePersonIdList = this.carLotBuyPersonService.getBuyHousePersonIdListByCarLotId(carLotId);
        } else if (storageRoomId != 0) {
            buyHousePersonIdList = this.storageRoomPersonService.getBuyHousePersonIdListByStorageRoomId(storageRoomId);
        } else if (shopHouseId != 0) {
            buyHousePersonIdList = this.shopHouseBuyPersonService.getBuyHousePersonIdListByShopHouseId(shopHouseId);
        }

        List<BuyHousePerson> buyHousePersonList = this.buyHousePersonService.getBuyHousePersonListByContractId(contractId);//
        if (CollectionUtils.isNotEmpty(buyHousePersonList)) {
            Map<String, Object> item = null;
            Boolean isShow = false;
            for (BuyHousePerson buyHousePerson : buyHousePersonList) {
                isShow = false;
                item = null;
                item = Maps.newHashMap();
                item.put("id", buyHousePerson.getId());
                isShow = buyHousePersonIdList.contains(buyHousePerson.getId().toString());
                item.put("LAY_CHECKED", isShow);
                item.put("contractName", contract.getName());
                item.put("buyHousePersonName", buyHousePerson.getName());
                item.put("idCard", buyHousePerson.getIdCard());
                item.put("tel", buyHousePerson.getTel());
                listData.add(item);
            }
        }
        return LayUiUtils.list(listData);
    }

    /**
     * 购房人数据登记
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("chooseBuyPersonForm")
    @RequiresPermissions("resetAgreement:chooseBuyPersonForm")
    public void chooseBuyPersonForm(HttpServletRequest request, ModelMap modelMap) {
        Integer buyHousePersonId = ParamUtils.getInt(request, "buyHousePersonId", 0);
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        BuyHousePerson buyHousePerson = this.buyHousePersonService.findOne(buyHousePersonId);
        Contract contract = this.contractService.findOne(contractId);
        buyHousePerson = buyHousePerson == null ? new BuyHousePerson() : buyHousePerson;
        modelMap.addAttribute("buyHousePerson", buyHousePerson);
        modelMap.addAttribute("contract", contract);
    }

    /**
     * 验证产权人身份证号是否已存在
     *
     * @param request
     * @return
     */
    @RequestMapping("validateIdCard")
    @ResponseBody
    @RequiresPermissions("resetAgreement:validateIdCard")
    public String validateIdCard(HttpServletRequest request) {
        String idCard = ParamUtils.getString(request, "idCard", "");
        int buyHousePersonId = ParamUtils.getInt(request, "buyHousePersonId", 0);
        int contractId = ParamUtils.getInt(request, "contractId", 0);
        String msg = this.buyHousePersonService.validateIdCard(contractId, buyHousePersonId, idCard);//返回的验证信息
        return msg;
    }

    /**
     * 购房人数据保存
     *
     * @param request
     * @return
     * @throws AjaxException
     */
    @RequestMapping("buyHousePersonSave")
    @ResponseBody
    @RequiresPermissions("resetAgreement:buyHousePersonSave")
    public synchronized Response contractSave(HttpServletRequest request) throws AjaxException {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        Integer buyHousePersonId = ParamUtils.getInt(request, "buyHousePersonId", 0);
        BuyHousePerson buyHousePerson = this.buyHousePersonService.findOne(buyHousePersonId);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "1111", "该户不存在！");
        Set<SysRole> list = WebUtils.getLoginUserInfo().getRoleList();
        String doName = "";
        for (SysRole sysRole : list) {
            doName = doName + "-" + sysRole.getRole() + "-";
        }
        if (doName.contains("-管理员-")) {

        } else if (doName.contains("-物业管理员-") || doName.contains("-物业操作员-")) {
            Precondition.checkAjaxArguement(contract.getTakeHouseStatus() != null && contract.getTakeHouseStatus().equals(Status.YES.getIndex()), "1111", "该家庭暂未交房！");
        } else {
/*
            Precondition.checkAjaxArguement(contract.getLimitStatus() != null && contract.getLimitStatus().equals(Status.NO.getIndex()), "4444", "该家庭当前暂不能进行操作！");
*/
        }
        buyHousePerson = buyHousePerson == null ? new BuyHousePerson() : buyHousePerson;
        WebUtils.bind(request, buyHousePerson);
        buyHousePerson.setContract(contract);
        this.buyHousePersonService.save(buyHousePerson);
        return new Response("0001", "保存成功！");
    }

    /**
     * 删除产权人
     *
     * @param request
     * @return
     */
    @RequestMapping("delBuyHousePersonById")
    @ResponseBody
    @RequiresPermissions("resetAgreement:delBuyHousePersonById")
    public synchronized Response delBuyHousePersonById(HttpServletRequest request) {
        Integer buyHousePersonId = ParamUtils.getInt(request, "buyHousePersonId", 0);
        BuyHousePerson buyHousePerson = this.buyHousePersonService.findOne(buyHousePersonId);
        Precondition.checkAjaxArguement(buyHousePerson != null, "1111", "数据错误！");
        this.carLotBuyPersonService.deleteCarLotBuyPersonByBuyHousePersonId(buyHousePerson.getId());
        this.houseBuyPersonService.deleteHouseBuyPersonByBuyHousePersonId(buyHousePerson.getId());
        this.storageRoomPersonService.deleteStorageRoomBuyPersonByBuyHousePersonId(buyHousePerson.getId());
        this.buyHousePersonService.delete(buyHousePerson.getId());
        this.actionHistoryService.saveActionHistoryByContractId(buyHousePerson.getContract().getId(), "删除产权人" + buyHousePerson.getName() + buyHousePerson.getIdCard(), "删除产权人");
        return new Response("0001", "删除成功");
    }

    /**
     * 保存产权人信息
     *
     * @param request
     * @return
     */
    @RequestMapping("setBuyHousePersonData")
    @ResponseBody
    @RequiresPermissions("resetAgreement:setBuyHousePersonData")
    public synchronized Response setBuyHousePersonData(HttpServletRequest request) {
        String idsString = ParamUtils.getString(request, "ids", "");
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        Integer carLotId = ParamUtils.getInt(request, "carLotId", 0);
        Integer storageRoomId = ParamUtils.getInt(request, "storageRoomId", 0);
        Integer shopHouseId = ParamUtils.getInt(request, "shopHouseId", 0);
        String[] ids = null;
        if (!idsString.equals("")) {
            ids = idsString.split(",");
        }
        String result = this.buyHousePersonService.setBuyHousePerson(ids, houseId, carLotId, storageRoomId,shopHouseId);
        String ok = "ok";
        if (ok.equals(result)) {
            return new Response("0001", "设置成功");

        }
        return new Response("0002", "设置失败");
    }


    /**
     * 保存审批表基础信息
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("setSpForm")
    @RequiresPermissions("resetAgreement:setSpForm")
    public void forSpForm(HttpServletRequest request, ModelMap modelMap) {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkSqdsArguement(contract != null, "该户协议不存在");
        modelMap.addAttribute("contract", contract);

    }

    /**
     * 审批表页面信息保存
     *
     * @param request
     * @return
     */
    @RequestMapping("saveSpForm")
    @ResponseBody
    @RequiresPermissions("resetAgreement:saveSpForm")
    public Response saveSpForm(HttpServletRequest request) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "0012", "找不到该户信息！");
        WebUtils.bind(request, contract);
        this.contractService.save(contract);
        CalculateUtils.main(contract.getId());
        this.actionHistoryService.saveActionHistoryByContractId(contract.getId(), "保存审批表信息", "审核状态");

        Response response = new Response();
        response.setCode("0001");
        return response;
    }

    /**
     * 产权人关系类型保存页面
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("setBuyHousePersonTypeForm")
    @RequiresPermissions("resetAgreement:setBuyHousePersonTypeForm")
    public void setBuyHousePersonTypeForm(HttpServletRequest request, ModelMap modelMap) {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkSqdsArguement(contract != null, "该户协议不存在");
        List<BuyHousePerson> buyHousePersonList = this.buyHousePersonService.getBuyHousePersonListByContractId(contractId);//

        modelMap.addAttribute("contract", contract);
        modelMap.addAttribute("buyHousePersonList", buyHousePersonList);

    }

    /**
     * 产权人关系类型保存
     *
     * @param request
     * @return
     * @throws AjaxException
     */
    @RequestMapping("setBuyHousePersonTypeSave")
    @ResponseBody
    @RequiresPermissions("resetAgreement:setBuyHousePersonTypeSave")
    public synchronized Response setBuyHousePersonTypeSave(HttpServletRequest request) throws AjaxException {
        Response response = this.buyHousePersonService.savBuyHousePersonType(request);
        return response;
    }

}
